
package cn.jaye.fabric.common.filter;

import cn.jaye.fabric.common.exception.ServiceException;
import cn.jaye.fabric.common.model.InputBody;
import com.alibaba.fastjson.JSON;
import cn.jaye.fabric.common.constant.ExceptionEnum;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * @author Jaye
 * @create 2017-12-01 17:26
 */

public class MyHttpServletRequestWrapper extends HttpServletRequestWrapper {

    private final byte[] body;

    public MyHttpServletRequestWrapper(HttpServletRequest request)
            throws IOException {
        super(request);
        StringBuffer buffer = new StringBuffer();
        BufferedReader reqbuf = new BufferedReader(new InputStreamReader(request.getInputStream()));
        String str = null;
        while ((str = reqbuf.readLine()) != null) {
            buffer.append(str);
        }
        InputBody inputBody;
        try {
            inputBody = JSON.parseObject(buffer.toString(), InputBody.class);
            if (inputBody.getData() != null) {
                body = JSON.toJSONString(inputBody.getData()).getBytes("utf-8");
            } else {
                throw new ServiceException(ExceptionEnum.INVALID_PARAMETER);
            }
        }catch (Exception e){
            throw new ServiceException(ExceptionEnum.INVALID_PARAMETER);
        }
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        final ByteArrayInputStream bais = new ByteArrayInputStream(body);
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bais.read();
            }
        };
    }
}
